package com.example.demo.Controller;

import com.example.demo.pojo.Furn;
import com.example.demo.service.furnService.FurnService;
import com.example.demo.utils.PathUtil;
import com.example.demo.utils.UploadFileUtils;
import com.example.demo.utils.WebUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/furn")
public class FurnController {
@Resource
    FurnService furnService;


@GetMapping("/list")
    public String showFurn(Model model){

    List<Furn> allFurn = furnService.findAllFurn();
    model.addAttribute("allFurn",allFurn);
     return  "furn_manage";
}



    @RequestMapping("/furnByPage")
    public  String listFurnsByPage(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize,Model model,HttpSession session){

        //使用 PageHelper
        //设置分页参数
        PageHelper.startPage(pageNum,pageSize);
        List<Furn> allFurn = furnService.findAllFurn();
        //System.out.println("ok");
        //将分页查询的结果 封装到 PageInfo
        //PageInfo 包含了分页的各个信息
        PageInfo pageInfo = new PageInfo(allFurn, pageSize);
        //System.out.println("pageInfo:"+pageInfo);

        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("allFurn",allFurn);

        //封装到Msg返回给前端

        return  "furn_manage";

    }

    @GetMapping("/addFurn")
    public  String addFurn(){
    return "furn_add";
    }
    @PostMapping("/addFurn")
    public  String addfurn(Furn furn){

        boolean b = furnService.insertIntoFurn(furn);
        if (b){
            return "redirect:/furn/furnByPage";
        }

        return  "add_fail";
    }



    @GetMapping("/selectFurnById")
    public  String selectFurnById(Integer id, HttpSession session){
        Furn furn = furnService.selectFurnById(id);
//        System.out.println("furn:"+furn.toString());
        session.setAttribute("id_furn",furn);

        return  "furn_update";
    }

    @PostMapping("/updateFurn")
    public  String updateFurn(Furn furn, HttpSession session, @RequestPart(value = "imgPath1",required = false) MultipartFile file, HttpServletRequest request) throws IOException, URISyntaxException {
        Furn id_furn = (Furn) session.getAttribute("id_furn");

        furn.setId(id_furn.getId());
        System.out.println(file);
        System.out.println(file.getOriginalFilename());
        if (StringUtils.hasLength(file.getOriginalFilename())&& file!=null){

            String suffixName = UploadFileUtils.getSuffixName(file);
            String newFileName = UploadFileUtils.getNewFileName(suffixName);
            //1.给文件起一个新的文件名

            String realpath = System.getProperty("user.dir") + "\\upload\\";
            //System.getProperty("user.dir")获取当前项目在本机上的物理地址，
            //realpath图片在本机（或服务器上）的物理存储地址，
            File fileDirectory = new File(realpath);//在内存中创建文件夹映射对象
            File destFile = new File(realpath + newFileName);//在内存中创建文件映射对象
            if (!fileDirectory.exists() && !fileDirectory.mkdir()) {//创建本机的真实目录
                System.out.println("文件夹创建失败！");
                return "update_fail";
            }
            //2.在本机上（或服务器）创建一个文件夹

            file.transferTo(destFile);

            //3.把file以新的文件名形式存到那个文件夹

            //4.创建能访问该图片的URL地址（不是电脑的物理地址、不是绝对路径）放入数据库表
            URI uri = new URI(request.getRequestURL()+"");
            uri=UploadFileUtils.getHost(uri);
            String sqlImg=uri+"/upload/"+newFileName;
            furn.setImgPath(sqlImg);

        }

        boolean b = furnService.UpdateFurn(furn);
        if (b){
            return  "redirect:/furn/furnByPage";
        }
        else {
            return "update_fail";
        }



    }
          @GetMapping("/deleteFurn")
    public  String  deleteFurnById(Integer id){
              boolean b = furnService.deleteFurnById(id);
              if (b){
                  return "redirect:/furn/furnByPage";
              }else {
                  return "update_fail";
              }

          }
}
